Using my random number code, write a script that gets a random number between 1 and 100 when you click on a link. If the number returned is less than 50, throw up one message ("Hey, 32 is less than 50."). If it's 50 or greater, throw up an alternate message ("Yo, 77 is greater than or equal to 50.").
Exercise: Add a for statement to loop through the thing five times with every click of the link.
Exercise: Now, instead of looping five times, have it loop a random number of times (between 1 and 8). Before the loop starts, throw up an alert box stating "I will execute the loop X times.", X being the random number between 1 and 8, then execute the loop X times. Confusing? Probably, but hey, we're way beyond Hello World and I did warn you that things could get rough. Besides, if you've made it this far, and you at least have half a clue what you're doing, then I'd say you're doing just fine! Keep plugging away!
Exercise: Alter your last exercise to loop a random number of times between 4 and 9 rather than 1 and 8. Do not alter the random number generator. Use getRandom() exactly as-is for both tasks.
This is an example of creative problem solving. I've told you that programming is an exercise in logic. Well, it's just as much an exercise in problem solving... how to trim that square peg so it fits neatly into the round hole.
Here is a simple function that might come in handy from time to time. Send it three numbers and it averages them...
function myAverager(num1,num2,num3) { averaged = ( (num1*1) + (num2*1) + (num3*1) ) / 3; } |
(We multiply each number by 1 just in case the browser thinks numX is a string. If we don't 13 + 39 might end up as 1339)
Notice that right now, the function simply performs the arithmetic. It doesn't return anything. We can make it return "averaged" by adding the following line...
function myAverager(num1,num2,num3) { averaged = ( (num1*1) + (num2*1) + (num3*1) ) / 3; return averaged; } |
Or even more simply...
function myAverager(num1,num2,num3) { return ( (num1*1) + (num2*1) + (num3*1) ) / 3; } |
Exercise: Using the last function above without any changes, create a script with three text input boxes and a button. When the button is pressed, an alert box is thrown up that says something like...
The average of 10, 22 and 13 is 15.
Your solution should be to grab the three values, send them to myAverager() and pop up an alert box with the answer.
Exercise: Make your last exercise round the answer to two decimal places.
<< BACK NEXT >> |
Javascript Reference irt.org/Javascript FAQ Deja Power Search Joke Break |
Print version available - Get the PageTutor book & CD |
|
|